package com.zhkj.txg.module.member.ui

import android.content.Intent
import android.view.View
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import com.zhkj.lib.base.BalanceChangeEvent
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.RxBus
import com.zhkj.txg.R
import com.zhkj.txg.module.mine.ui.BindAliPayActivity
import com.zhkj.txg.module.mine.vm.BalanceViewModel
import com.zhkj.txg.module.order.entity.OrderPayEntity
import com.zhkj.txg.module.order.ui.OnItemClickListener
import com.zhkj.txg.module.order.ui.SimplePopupWindow
import com.zhkj.txg.utils.TextWatcherWrapper
import com.zhkj.txg.utils.ThirdLoginUtils
import kotlinx.android.synthetic.main.activity_member_withdraw.*
import java.math.BigDecimal
import java.math.RoundingMode

class MemberWithdrawActivity : ViewModelActivity<BalanceViewModel>() {

    private val requestCodeBind = 1090

    override fun setViewModel(): BalanceViewModel = createViewModel()
    override val layoutResId: Int = R.layout.activity_member_withdraw
    override fun statusTitleBar(): View? = titleBar

    override fun initUI() {
        titleBar.setRightClickListener(View.OnClickListener {
            MemberWithdrawListActivity.member(this)
        })
        // 输入金额监听
        etBalance.addTextChangedListener(TextWatcherWrapper { s ->
            if (!s.isNullOrEmpty()) {
                // 第一步，先格式化数据格式
                if (s.contains('.')) {
                    val index = s.indexOf('.')
                    if (index == 0) s.insert(0, "0") // 金额以'.'开头
                    else if (index < s.lastIndex - 2)// 金额小数大于两位 例如:11.2236
                        s.delete(index + 3, s.length)
                }
                // 第二步，再比较金额大小
                viewModel.withdrawConfigLiveData.value?.response?.data?.let {
                    val balance = BigDecimal(it.money)
                    val currentAmount = BigDecimal(s.toString())
                    if (currentAmount > balance) {// 输入金额大于余额
                        s.replace(0, s.length, balance.toPlainString())
                        etBalance.setSelection(etBalance.text?.length ?: 0)
                        tvBalanceExpect.text = getString(R.string.except_format, balance.toPlainString())
                    } else {
                        val account = calculateExceptWithdraw(s.toString(), it.serviceRatio)
                        tvBalanceExpect.text = getString(R.string.except_format, account)
                    }
                }
            } else tvBalanceExpect.text = getString(R.string.except_format, "0")
        })
        // 跳转绑定支付宝页面
        tvBindingAliPay.setOnClickListener {
            viewModel.withdrawConfigLiveData.value?.response?.data?.let {
                if (!it.isBindAliPay) BindAliPayActivity.bind(this, requestCodeBind)
            }
        }
        // 绑定微信
        tvBindingWeChat.setOnClickListener {
            viewModel.withdrawConfigLiveData.value?.response?.data?.let {
                if (!it.isBindWeChat) ThirdLoginUtils.wxLogin(this)
            }
        }
        viewAliPay.setOnClickListener {
            viewModel.withdrawConfigLiveData.value?.response?.data?.let {
                if (!it.isBindWeChat) return@setOnClickListener
            }
            viewAliPay.isSelected = true
            viewWxPay.isSelected = false
        }
        viewWxPay.setOnClickListener {
            viewModel.withdrawConfigLiveData.value?.response?.data?.let {
                if (!it.isBindWeChat) return@setOnClickListener
            }
            viewAliPay.isSelected = false
            viewWxPay.isSelected = true
        }
        btnAddAddress.setOnClickListener {
            if (etBalance.text.isNullOrEmpty()) {
                toast(getString(R.string.money_invalid))
                return@setOnClickListener
            }
            viewModel.withdrawConfigLiveData.value?.response?.data?.let { entity ->
                if (entity.canWithdraw != "1") { // 提现功能是否开启
                    toast(getString(R.string.withdraw_close))
                    return@setOnClickListener
                }
                // 判断提现金额是否在区间之内
                val withdrawAmount = BigDecimal(etBalance.text.toString())
                val minWithdraw = BigDecimal(entity.minWithdrawAmount)
                if (minWithdraw > BigDecimal(0) && minWithdraw > withdrawAmount) {
                    toast(String.format(getString(R.string.withdraw_too_small), entity.minWithdrawAmount))
                    return@setOnClickListener
                }
                val maxWithdraw = BigDecimal(entity.maxServiceMoney)
                if (maxWithdraw > BigDecimal(0) && maxWithdraw < withdrawAmount) {
                    toast(String.format(getString(R.string.withdraw_too_large), entity.maxWithdrawAmount))
                    return@setOnClickListener
                }
                // 判断选中的支付方式是否有绑定
                val unbind =
                    (viewAliPay.isSelected && viewModel.withdrawConfigLiveData.value?.response?.data?.isBindAliPay == false)
                            || (viewWxPay.isSelected && viewModel.withdrawConfigLiveData.value?.response?.data?.isBindWeChat == false)
                if (unbind) {
                    toast(getString(R.string.bind_hint))
                    return@setOnClickListener
                }
                SimplePopupWindow(this).setTitle(
                    getString(
                        if (viewAliPay.isSelected) R.string.withdraw_ali_hint else R.string.withdraw_wx_hint
                    )
                ).setContent(
                    getString(
                        if (viewAliPay.isSelected) R.string.withdraw_ali_hint_content
                        else R.string.withdraw_wx_hint_content
                    )
                ).setConfirmCallback(object : OnItemClickListener {
                    override fun onClick(popupWindow: SimplePopupWindow) {
                        viewModel.memberWithdraw(
                            withdrawAmount.toPlainString(),
                            if (viewAliPay.isSelected) OrderPayEntity.TYPE_ALIPAY else OrderPayEntity.TYPE_WECHAT,
                            entity.withdrawToken
                        )
                        popupWindow.dismiss()
                    }
                }).showPopupWindow()
            }
        }
    }

    override fun initData() {
        viewModel.memberWithdrawConfig()
        viewAliPay.isSelected = true
        tvBalanceExpect.text = getString(R.string.except_format, "0")
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == requestCodeBind) {
            val account = data?.getStringExtra("data")
            if (!account.isNullOrEmpty()) viewModel.memberWithdrawConfig()
        }
    }

    override fun initViewModel() {
        // 提现配置数据观察者
        viewModel.withdrawConfigLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let {
                if (it.canWithdraw != "1") {
                    etBalance.isEnabled = false
                    btnAddAddress.isEnabled = false
                    toast(getString(R.string.withdraw_close))
                    return@let
                }
                etBalance.hint = String.format(getString(R.string.member_withdraw_hint), it.money)
                // 判断支付宝是否已绑定
                if (it.isBindAliPay) {
                    ivAliPay.visibility = View.VISIBLE
                    tvBindingAliPay.text = it.aliPayAccount
                    tvBindingAliPay.setTextColor(
                        ContextCompat.getColor(this, R.color.colorDefaultText)
                    )
                }
                tvBindingAliPay.visibility = View.VISIBLE
                // 判断微信是否已绑定
                if (it.isBindWeChat) {
                    ivWeChat.visibility = View.VISIBLE
                    tvBindingWeChat.text = it.weChatAccount
                    tvBindingWeChat.setTextColor(
                        ContextCompat.getColor(this, R.color.colorDefaultText)
                    )
                }
                tvBindingWeChat.visibility = View.VISIBLE
            }
        })
        // 提现结果数据观察者
        viewModel.withdrawLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) {
                toast(response.response?.msg ?: getString(R.string.withdraw_success))
                // 提现成功，刷新余额
                viewModel.refreshBalance()
                // 余额刷新
                RxBus.post(BalanceChangeEvent())
            }
            // 重新获取提现token
            if (response.status != HttpResponseStatus.Status.START) viewModel.memberWithdrawConfig()
        })
        // 微信授权数据观察者
        viewModel.weChatBindSubscribe().observe(this, Observer {
            if (it.success) viewModel.bindWeChat(it.code)
        })
        // 微信绑定数据观察者
        viewModel.bindWeChatLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) viewModel.memberWithdrawConfig()
        })
    }

    private fun calculateExceptWithdraw(origin: String, ratio: String): String {
        val realRatio = (100 - ratio.toInt()) / 100.0
        return BigDecimal(origin).multiply(BigDecimal(realRatio)).setScale(2, RoundingMode.HALF_UP).toPlainString()
    }
}